//

#import "ThemeTableView.h"
#import "BaseViewController.h"
#import "ThemeCell.h"
#import "Util.h"
#import "ThemeEmptyCell.h"
#import "ThemeLoadCell.h"
#import "SJAvatarBrowser.h"
#import "UIImageView+WebCache.h"
#import "ThemeInfoViewController.h"
@implementation ThemeTableView
{
    AFHTTPRequestOperationManager *_manager;
    BOOL _uploading;
    BOOL _isLastPage;
    ThemeLoadCell *_loadingCell;
    UITableViewCell *_emptyCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_isempty || _isload) {
        return kScreenHeight-50;
    }
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    _emptyCell = [ThemeEmptyCell createWithTableView:self];
    _loadingCell = [ThemeLoadCell createWithTableView:self];
    _testActivityIndicator=_loadingCell.testActivityIndicator;
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    _emptyCell = [ThemeEmptyCell createWithTableView:self];
    _loadingCell = [ThemeLoadCell createWithTableView:self];
    _testActivityIndicator=_loadingCell.testActivityIndicator;
    return self;
}

//  父类中已经添加了tableview的代理
-(void)initData{
    NSLog(@"%@",_search);
    _isload=YES;
    _nilArray = [[NSMutableArray alloc] init];
    _manager = [AFHTTPRequestOperationManager manager];
    //  NSString *url=[NSString stringWithFormat:@"%@chat/getCollection",BaseURL];
    NSDictionary *parameters = @{@"memberid":@4,@"size":@"20",@"endid":@"0"};
    AFHTTPRequestOperation*op= [_manager POST:@"http://testapp.1000fishing.com/api/chat/getCollection"  parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        NSData *jsonData = [[dic valueForKey:@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *result  = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"%@",dic);
        if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
            for (int i = 0; i<[result count]; i++) {
                NSDictionary *c= result[i];
                [_nilArray addObject:c];
            }
        }
        
        
        if (_nilArray!=nil&&_nilArray.count>0) {
            _isempty=NO;
            [self showfootView];//显示footView
            if ([_nilArray count]<20) {
                [self setIsLastPage:YES];
            }else{
                [self setIsLastPage:NO];
            }
        }else{
            _isempty=YES;
        }
        _isload=NO;
        [self reloadData];
        [self doneLoadingTableViewData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [self doneLoadingTableViewData];
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
}
-(void)initLastData{
    if (_nilArray!=nil&&_nilArray.count>0) {
        
        
        NSDictionary *c =[_nilArray objectAtIndex:[_nilArray count]-1];
        _manager = [AFHTTPRequestOperationManager manager];
        // NSString *url=[NSString stringWithFormat:@"%@chat/getCollection",BaseURL];
        _lastid =[c valueForKey:@"id"];
        NSDictionary *parameters = @{@"memberid":@4,@"size":@"20",@"endid":_lastid};
        AFHTTPRequestOperation*op= [_manager POST:@"http://testapp.1000fishing.com/api/chat/getCollection" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSError*error;
            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
            NSData *jsonData = [[dic valueForKey:@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *result  = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
            NSLog(@"%@",dic);
            if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
                for (int i = 0; i<[result count]; i++) {
                    NSDictionary *data= result[i];
                    
                    [_nilArray addObject:data];
                    NSMutableArray *indexPathArray = [NSMutableArray array];
                    NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPathArray addObject:tempIndexPath];
                    [self insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
                    
                }
                if (result.count < 20) {
                    [self setIsLastPage:YES];
                    
                }else [self setIsLastPage:NO];
            }else{
                [self setIsLastPage:YES];
            }
            [self reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        }];
        op.responseSerializer = [AFCompoundResponseSerializer serializer];
        [op start];
    }
}//实现TABLE方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%lu",(unsigned long)_nilArray.count);
    if (_isempty || _isload) {
        return 1;
    }else{
        return _nilArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isload) {
        [_testActivityIndicator startAnimating];
        [self hiddenfootView];
        return _loadingCell;
    }
    
    
    [_testActivityIndicator stopAnimating];
    if (_isempty) {
        [self hiddenfootView];
        return _emptyCell;
    }
    ThemeCell *cell = [ThemeCell createWithTableView:tableView];
    for (UIView *view in [cell.content subviews]) {
        if (view.tag == 3000) {
            [view removeFromSuperview];
        }
    }
    if (_nilArray!=nil&&_nilArray.count>0) {
        NSDictionary *d = [_nilArray objectAtIndex:indexPath.row];
        cell.name.text=d[@"name"];
        cell.time.text =d[@"collection_date"];
        NSString *headurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,[d valueForKey:@"head"]];
        [cell.head sd_setImageWithURL:[NSURL URLWithString:headurl]];
        if (cell.head.image==nil) {
            [cell.head setImage:[UIImage imageNamed:@"head"]];
        }
        //文本内容高度
        NSString * s =[d valueForKey:@"path"];
        cell.content.text = [d valueForKey:@"content"];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSLineBreakByWordWrapping;
        NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14], NSParagraphStyleAttributeName: paragraph};
        CGSize size = [cell.content.text boundingRectWithSize:CGSizeMake(290, 9999) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
        if(size.height>85){
            cell.contentHeight.constant = 85;
            
        }else{
            cell.contentHeight.constant = size.height;
            
        }
        
        NSNumber *type = d[@"collection_type"];
        //文本下方图片
         cell.contentImageView.hidden = YES;
        if ([type isEqualToNumber:@0]){
            if (![s isEqualToString:@""]) {
                //图片路径
                 NSArray *imgArray =[s componentsSeparatedByString:@","];
                if (imgArray.count<=3) {
                    for (int i=0; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100), 0, 90, 90)];
                        cimg.tag = 3000;
                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    cell.imageHeight.constant=100;
                    CGRect rect = cell.frame;
                    rect.size.height = 110+cell.contentHeight.constant+100;
                    cell.frame = rect;
                    cell.contentImageView.hidden = NO;
                }else if (imgArray.count>3&&imgArray.count<=6){
                    for (int i=0; i<3; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100), 0, 90, 90)];
                        cimg.tag = 3000;
                        
                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    for (int i=3; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-3)*(100), 100, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;
                        
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    cell.imageHeight.constant=200;
                    CGRect rect = cell.frame;
                    rect.size.height = 110+cell.contentHeight.constant+200;
                    cell.frame = rect;
                    cell.contentImageView.hidden = NO;
                }else if (imgArray.count>6){
                    for (int i=0; i<3; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake(i*(100), 0, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;
                        
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    
                    for (int i=3; i<6; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-3)*(100), 100, 90, 90)];
                        NSString *str = imgArray[i];
                        cimg.tag = 3000;
                        
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    for (int i=6; i<imgArray.count; i++) {
                        UIImageView *cimg = [[UIImageView alloc] initWithFrame:CGRectMake((i-6)*(100), 200, 90, 90)];
                        cimg.tag = 3000;
                        
                        NSString *str = imgArray[i];
                        NSString *imageurl = [NSString stringWithFormat:@"%@%@",BaseImageURL,str];
                        [cimg sd_setImageWithURL:[NSURL URLWithString:imageurl]];
                        if (cimg.gestureRecognizers.count == 0) {
                            cimg.userInteractionEnabled = YES;
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                            [cimg addGestureRecognizer:tap];
                        }
                        [cell.contentImageView addSubview:cimg];
                    }
                    cell.imageHeight.constant=300;
                    CGRect rect = cell.frame;
                    rect.size.height = 110+cell.contentHeight.constant+300;
                    cell.frame = rect;
                    cell.contentImageView.hidden = NO;
                }
            }else{
                CGRect rect = cell.frame;
                rect.size.height = 110+cell.contentHeight.constant;
                cell.frame = rect;
            }

        }
        
        [cell setNeedsDisplay];
        
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ThemeInfoViewController *l = [[ThemeInfoViewController alloc] init];
    [self.viewController.navigationController pushViewController:l animated:YES];
}
-(void)showImage:(UITapGestureRecognizer *)imageView{
    UIImageView* i =(UIImageView*) imageView.view;
    if (i.image!=nil) {
        [SJAvatarBrowser showImage:i];//调用方法
    }
}
@end